package net.sudot.chess.business.dao;

import net.sudot.chess.business.dto.GameDetailDTO;
import net.sudot.chess.business.model.Game;
import net.sudot.chess.business.model.Room;
import org.springframework.stereotype.Repository;

import javax.persistence.TypedQuery;
import java.util.List;

/**
 * 游戏
 *
 * @author tangjialin on 2018-02-27.
 */
@Repository
public class GameDao extends BaseDao<Game> {
    /**
     * 获取游戏分类下的游戏
     *
     * @param categoryId 游戏分类主键
     * @return 返回游戏信息
     */
    public List<Game> findByCategory(Long categoryId) {
        String ql = "SELECT game FROM Game game WHERE game.deleted = false AND game.categoryId = :categoryId";
        TypedQuery<Game> query = entityManager.createQuery(ql, entityClass);
        query.setParameter("categoryId", categoryId);
        return query.getResultList();
    }

    /**
     * 获取游戏分类下的游戏详细信息
     *
     * @param categoryId 游戏分类主键
     * @return 返回游戏详细信息
     */
    public List<GameDetailDTO> findDetailByCategory(Long categoryId) {
        StringBuilder ql = new StringBuilder("SELECT new net.sudot.chess.business.dto.GameDetailDTO(game, room)" +
                " FROM Game game" +
                " LEFT JOIN Room room ON room.gameId = game.id AND (room.id IS NULL OR room.status = :status)" +
                " WHERE game.deleted = false");
        if (categoryId != null && categoryId > 0L) {
            ql.append(" AND game.categoryId = :categoryId");
        }
        ql.append(" ORDER BY room.people DESC, room.maxPeople - room.people ASC");
        TypedQuery<GameDetailDTO> query = entityManager.createQuery(ql.toString(), GameDetailDTO.class);
        if (categoryId != null && categoryId > 0L) {
            query.setParameter("categoryId", categoryId);
        }
        query.setParameter("status", Room.Status.WAIT);
        return query.getResultList();
    }
}
